package com.yang.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yang.utils.JsonUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.yang.pojo.User;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller//或者直接使用@RestController也不走视图解析器，会直接返回一个字符串
public class UserController {
    @RequestMapping(value = "/j5")
    @ResponseBody//+@Controller它就不会走视图解析器，会直接返回一个字符串
    public String json5(){
        //创建一个对象
        User s = new User("杨同宇",3,"男");
        System.out.println(s.toString());
        return s.toString();
    }
    @RequestMapping(value = "/j1")
    @ResponseBody//+@Controller它就不会走视图解析器，会直接返回一个字符串
    public String json1() throws JsonProcessingException {

        //jackson里有一个对象:objectMapper
        ObjectMapper mapper = new ObjectMapper();
        //创建一个对象
        User user = new User("杨同宇",3,"男");
        String s = mapper.writeValueAsString(user);
        System.out.println(s);
        return s;
    }
    @RequestMapping(value = "/j2")
    @ResponseBody//+@Controller它就不会走视图解析器，会直接返回一个字符串
    public String json2() throws JsonProcessingException {

        //jackson里有一个对象:objectMapper
        ObjectMapper mapper = new ObjectMapper();
        List<User> userList = new ArrayList<User>();
        //创建多个对象
        User user1 = new User("杨同宇1",3,"男");
        User user2 = new User("杨同宇2",3,"男");
        User user3 = new User("杨同宇3",3,"男");
        User user4 = new User("杨同宇4",3,"男");
        userList.add(user1);
        userList.add(user2);
        userList.add(user3);
        userList.add(user4);
        String s = mapper.writeValueAsString(userList);//new ObjectMapper().writeValueAsString(userList);
        return s;
    }
    @RequestMapping(value = "/j3")
    @ResponseBody//+@Controller它就不会走视图解析器，会直接返回一个字符串
    public String json3() throws JsonProcessingException {

        //jackson里有一个对象:objectMapper
        ObjectMapper mapper = new ObjectMapper();
        Date date = new Date();
        //自定义日期格式
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // ObjectMapper,时间解析后的默认格式为Timestamp,时间戳
        String s = mapper.writeValueAsString(format.format(date));//new ObjectMapper().writeValueAsString(date);
        return s;
    }
    @RequestMapping(value = "/j4")
    @ResponseBody//+@Controller它就不会走视图解析器，会直接返回一个字符串
    public String json4() throws JsonProcessingException {
        Date date = new Date();
        return new JsonUtils().getJson(date,"yyyy-MM-dd HH:mm:ss");//return new JsonUtils.getJson(date);
    }

}
